<?php

namespace app\common\model;

use app\helpers\Common;
use app\libs\traits\BaseModelTrait;
use app\common\model\File;

use think\model\concern\SoftDelete;

class VueAdmin extends Base
{
    /**
     * Base Model Trait
     */
    use BaseModelTrait;

    use SoftDelete;

    protected $deleteTime = 'deleted_at';

    // 软删除字段默认值
    protected $defaultSoftDelete = 0;

    // 数据表名称
    //protected $table = 'vue_admins';

    // 当前模型名称 不带前缀
    protected $name = 'vue_admins';

    // 主键
    protected $pk = 'id';

    // 字段验证规则
    protected $validate = true;

    // 设置字段信息
//    protected $field = [
//        'id' => 'int',
//        'created_id' => 'int',
//        'created_at' => 'int',
//        'updated_id' => 'int',
//        'updated_at' => 'int',
//        'deleted_id' => 'int',
//        'deleted_at' => 'int',
//        'username' => 'string',
//        'email' => 'string',
//        'sorting' => 'int',
//        'status' => 'int'
//    ];

    // 设置废弃字段
    protected $disuse = [
        'remember_token'
    ];

    // 定义全局的查询范围
    protected $globalScope = ['status'];

    public function scopeStatus($query)
    {
        $query->where('status', '<>', config('constants.SOFT_DELETE_STATUS'));
    }

    public static function _after_insert($data)
    {
        // 头像
        if (isset($data['avatar']) && !empty($data['avatar'])) {
            File::where('file_url', $data['avatar'])->update(['related_id' => $data['id'], 'related_table' => 'admins', 'status' => 1]);
        }
    }

    public static function _after_update($data)
    {
        // 头像
        if (isset($data['avatar']) && !empty($data['avatar'])) {
            // 处理删除掉的文件
            File::where(['related_id' => $data['id'], 'related_table' => 'admins'])->where('file_url', '<>', $data['avatar'])->update(['status' => 0]);

            File::where('file_url', $data['avatar'])->update(['related_id' => $data['id'], 'related_table' => 'admins', 'status' => 1]);
        }
    }

    public static function _after_delete($id)
    {
        $data = self::find($id);
        // 头像
        if (isset($data['avatar']) && !empty($data['avatar'])) {
            File::where('file_url', $data['avatar'])->update(['status' => 0]);
        }
    }

    /**
     * Set sorting attribute
     *
     * @param $value
     * @return int
     */
    public function setSortingAttr($value)
    {
        //$this->field['sorting'] = !empty($value) ? $value : 0;
        return !empty($value) ? $value : 0;
    }

    public function getLastLoginTimeAttr($date)
    {
        if (!$date) {
            return '';
        }

        return date('Y-m-d H:i:s', $date);
    }

    /**
     * 格式化列表数据
     */
    public static function formatDatas($list, $params = '')
    {
        foreach ($list as &$item) {
            $item = self::formatItem($item, $params);
        }

        return $list;
    }

    /**
     * 格式化单个数据
     */
    public static function formatItem($item, $params = '')
    {
        if (!$item) {
            return '';
        }

        if ($item['avatar']) {
            $item['full_avatar'] = full_file_url($item['avatar']);
        } else {
            $avatar_text = $item['nickname'] ?? $item['username'];
            $item['full_avatar'] = letter_avatar($avatar_text);
        }
        if ($item['status'] == 1) {
            $item['status_name'] = '正常';
        } else {
            $item['status_name'] = '禁用';
        }
        // 角色
        /*if ($item['type'] == 0) {
            $item['role_names'] = '超级管理员';
        } else {
            // 角色
            $roleIds = AdminRoleUser::where('admin_id', $item['id'])->column('role_id');
            $item['role_ids'] = $roleIds;
            $roleNames = AdminRole::whereIn('id', $roleIds)->column('name');
            $item['role_names'] = implode('、', $roleNames);
        }*/
        $roleIds = VueAdminRoleUser::where('admin_id', $item['id'])->column('role_id');
        $item['role_ids'] = $roleIds;
        $roleNames = VueAdminRole::whereIn('id', $roleIds)->column('name');
        $item['role_names'] = implode('、', $roleNames);

        return $item;
    }

    /**
     * 删除
     */
    public static function doDelete($id)
    {
        VueAdminRoleUser::where('admin_id', $id)->delete();

        // 直接使用数据库的删除方法软删除无效
        //return self::where('id', $id)->delete();
        // 自定义软删除
        return self::where('id', $id)->update([
            //'deleted_at' => time(),
            'status' => config('constants.SOFT_DELETE_STATUS')
        ]);
    }

    /**
     * 获取管理员的路由菜单
     */
    public function getMenus($adminId, $isRoute = false)
    {
        $cacheKey = 'all_menus-' . $adminId;
        if ($isRoute) {
            $cacheKey = 'route_menus-' . $adminId;
        }
        $route_menus = cache($cacheKey);
        if (!$route_menus) {
            $adminMenuMdl = new \app\common\model\VueAdminMenu();
            $adminRoleUserMdl = new \app\common\model\VueAdminRoleUser();

            // 角色
            $roles = $adminRoleUserMdl->where('admin_id', $adminId)->with(['adminRole'])->select()->toArray();
            $accessStr = '';
            foreach ($roles as $item) {
                $adminRole = $item['adminRole'];
                $accessStr .= ',' . $adminRole['access'];
            }
            // 权限
            $access = array_unique(explode(',', substr($accessStr, 1)));
            if ($access) {
                $menuWhere = [
                    ['id', 'in', $access],
                    ['status', '=', 1]
                ];
                if ($isRoute) {
                    $menuWhere[] = ['is_route', '=', 1];
                }
                $menuDatas = $adminMenuMdl->where($menuWhere)->field('id, parent_id, name, app, controller, action, route, type, icon, sorting, icon2')->order('sorting', 'ASC')->select()->toArray();
            } else {
                $menuDatas = [];
            }
            $route_menus = [];
            foreach ($menuDatas as $menuData) {
                $route_menus[] = [
                    'id' => $menuData['id'],
                    'parent_id' => $menuData['parent_id'],
                    'name' => $menuData['name'],
                    'app' => $menuData['app'],
                    'controller' => $menuData['controller'],
                    'action' => $menuData['action'],
                    'route' => $menuData['route'],
                    'type' => $menuData['type'],
                    'icon' => $menuData['icon'],
                    'sorting' => $menuData['sorting'],
                    'icon2' => $menuData['icon2'],
                ];
            }

            // 用缓存不能用 * 查询，数据量大的时候清除缓存会有问题
            cache($cacheKey, $route_menus, null, 'admin');
        }

        return $route_menus;
    }
}
